package com.iring.service.common.impl;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.iring.dao.common.CallLogDao;
import com.iring.dao.common.DeviceDao;
import com.iring.domain.common.CallLog;
import com.iring.domain.common.DeviceInfo;
import com.iring.exception.ParamInvalidException;
import com.iring.service.common.CallLogService;
import com.iring.util.common.DateUtil;
import com.iring.exception.config.ErrorEnum;
import com.iring.vo.common.CallLogVO;
import com.iring.vo.pbx.PBXCdrInfo;
import com.iring.vo.pbx.PBXRes;
import com.iring.vo.pbx.UploadCdr;

/**
 * @author wanggan
 */
@Service
public class CallLogServiceImpl implements CallLogService {
    private static final Logger logger = LoggerFactory.getLogger(CallLogServiceImpl.class);

    @Autowired
    CallLogDao callLogDao;

    @Autowired
    DeviceDao deviceDao;

    private void checkStringParam(String str, String name) {
        if (null == str || str.trim().equals("")) {
            throw new ParamInvalidException(name + " is null");
        }
    }

    @Override
    public Page<CallLog> listCallLog(CallLogVO callLogVO, String username) {
        String mac = callLogVO.getMac();
        checkStringParam(mac, "mac");
        String start = callLogVO.getStartTime();
        checkStringParam(start, "starttime");
        String end = callLogVO.getEndTime();
        checkStringParam(end, "endtime");
        if (DateUtil.isStartAfterEnd(start, end)) {
            throw new ParamInvalidException("startTime is after than endTime");
        }
        DeviceInfo deviceInfo = deviceDao.findByMacAndUsername(mac,username);
        if(null == deviceInfo){
            throw new ParamInvalidException(ErrorEnum.USER_NOT_AUTHENTION);
        }
        Date startTime = DateUtil.parseToDate(DateUtil.addStartTimeSub(start));

        Date endTime = DateUtil.parseToDate(DateUtil.addEndTimeSub(end));
        Pageable pageable = callLogVO.getPage()
                .pageRequest();

        Boolean nosrc = false;
        String src = callLogVO.getSrc();
        if (src == null || src.trim().equals("")) {
            nosrc = true;
        }
        Boolean nodst = false;
        String dst = callLogVO.getDst();
        if (dst == null || dst.trim().equals("")) {
            nodst = true;
        }

        if (nosrc && nodst) {
            return callLogDao.findByMacAndStartTimeBetween(mac, startTime, endTime, pageable);
        } else if (nodst) {
            return callLogDao.findByMacAndStartTimeBetweenAndSrcContaining(mac, startTime, endTime,
                    src, pageable);
        } else if (nosrc) {
            return callLogDao.findByMacAndStartTimeBetweenAndDstContaining(mac, startTime, endTime,
                    dst, pageable);
        } else {
            return callLogDao.findByMacAndStartTimeBetweenAndSrcContainingAndDstContaining(mac,
                    startTime, endTime, src, dst, pageable);
        }
    }

    /**
     * 保存cdr
     *
     * @param uploadCdr
     *            Pbx的通话日志信息
     */
    @Transactional
    @Override
    public PBXRes saveCallLog(UploadCdr uploadCdr) {
        String type  = uploadCdr.getType();
        if (null == type || type.trim().equals("") ||!"cdrinfo".equals(type)) {
            return new PBXRes(201, "invalid cdr mark");
        }
        List<PBXCdrInfo> pbxCdrInfoList = uploadCdr.getInfo();
        if(pbxCdrInfoList.size()<=0){
            return new PBXRes(202, "cdr info is empty");
        }
        uploadCdr.getInfo().stream()
                .forEach((pbxCdrInfo)->{
            CallLog cdr = new CallLog();
            cdr.setCallStatus(pbxCdrInfo.getCall_status());
            cdr.setCallType(pbxCdrInfo.getCall_type());
            cdr.setDst(pbxCdrInfo.getCall_dest());
            cdr.setDuration(pbxCdrInfo.getDuration());
            cdr.setMac(pbxCdrInfo.getMac());
            cdr.setSrc(pbxCdrInfo.getCall_src());
            cdr.setStartTime(DateUtil.parseToDate(pbxCdrInfo.getStart_time()));
            callLogDao.save(cdr);
        });
        return new PBXRes();
    }
}
